﻿using IdentityModel;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;//JwtRegisteredClaimNames
using System.Security.Claims;
using System.Text;

namespace net8.Helper
{
    /// <summary>
    /// JWT帮助类
    /// </summary>
    public static class JwtHelper
    {
        public static string Encrypt(string payload)
        {
            JsonWebTokenHandler handler = new JsonWebTokenHandler();
            string token = handler.CreateToken(payload);
            return token;
        }

        public static string Encrypt(string secret, int a1)
        {
            List<string> roles = new List<string>() { "角色1", "角色2" };
            List<Claim> claims = [];
            claims.Add(new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            claims.Add(new Claim(ClaimTypes.Name, "api"));
            //claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            claims.AddRange(roles.Select(s => new Claim(ClaimTypes.Role, s)));
            //claims.Add(new Claim(JwtClaimTypes.Audience, "api"));
            //new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
            //new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
            ////这个就是过期时间，目前是过期1000秒，可自定义，注意JWT有自己的缓冲过期时间
            //new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds()}"),
            //new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(1000).ToString()),
            //new Claim(JwtRegisteredClaimNames.Iss, iss),
            //new Claim(JwtRegisteredClaimNames.Aud, aud),
            //new Claim(ClaimTypes.Role,tokenModel.Role),//为了解决一个用户多个角色(比如：Admin,System)，用下边的方法


            //var tokenHeader = httpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");

            //if (tokenHeader.Length >= 128)
            //{
            //    TokenModelJwt tm = JwtHelper.SerializeJwt(tokenHeader);

            //    //授权 Claim 关键
            //    var claimList = new List<Claim>();
            //    var claim = new Claim(ClaimTypes.Role, tm.Role);
            //    claimList.Add(claim);
            //    var identity = new ClaimsIdentity(claimList);
            //    var principal = new ClaimsPrincipal(identity);
            //    httpContext.User = principal;
            //}


            //秘钥 (SymmetricSecurityKey 对安全性的要求，密钥的长度太短会报出异常)
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken(
                issuer: "",
                claims: claims,
                signingCredentials: creds);

            var jwtHandler = new JwtSecurityTokenHandler();
            string token = jwtHandler.WriteToken(jwt);
            return token;
        }

        public static string Encrypt(string payload, string signKey)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signKey));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            JsonWebTokenHandler handler = new JsonWebTokenHandler();
            string token = handler.CreateToken(payload, credentials);
            return token;
        }
        /// <summary>
        /// 自定义认证
        /// </summary>
        /// <param name="services"></param>
        public static void AddRenZheng(this IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                //.AddAuthentication(o =>
                //{
                //    o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                //    o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                //})
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        // 设置签发方
                        ValidIssuer = "22",
                        // 验证签发方
                        ValidateIssuer = true,
                        // 设置接收方
                        ValidAudience = "111",
                        // 验证接收方
                        ValidateAudience = true,

                        // 验证生存期
                        ValidateLifetime = true,
                        // 过期时间容错值
                        ClockSkew = TimeSpan.FromSeconds(2),
                        //RequireExpirationTime = true,

                        // 验证签发方密钥
                        ValidateIssuerSigningKey = true,
                        // 签发方密钥
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("123456789123456789123456789123456789"))
                    };
                    //options.Events = new JwtBearerEvents()
                    //{
                    //    OnAuthenticationFailed = context =>
                    //    {
                    //        // 如果过期，则把<是否过期>添加到，返回头信息中
                    //        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                    //        {
                    //            context.Response.Headers.Add("Token", "renzhengguoqi");
                    //        }
                    //        return Task.CompletedTask;
                    //    }
                    //};
                });
        }

        public static void GetUserByToken()
        {
            var list = new List<Claim>();

            //list.Add(new Claim(ClaimTypes.Role, "管理员11"));
            //list.Add(new Claim(ClaimTypes.Email, "管理员22"));
            //list.Add(new Claim(ClaimTypes.NameIdentifier, "管理员33"));
            //list.Add(new Claim(ClaimTypes.Name, "管理员44"));
            //list.Add(new Claim(ClaimTypes.Actor, "管理员55"));
            //list.Add(new Claim(ClaimTypes.Sid, "管理员66"));
            list.Add(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "11"));

            var ddd = new ClaimsIdentity(list);
            var eee = new ClaimsPrincipal(ddd);
        }
    }

    //builder.Services.AddSingleton<IAuthorizationHandler, AppAuthorizeHandler>();//自定义策略授权
    public class AppAuthorizeHandler : IAuthorizationHandler
    {
        public Task HandleAsync(AuthorizationHandlerContext context)
        {
            return Task.CompletedTask;
        }
    }
}
